<?php

namespace App\Http\Controllers\v1;

use App\Models\User;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Http\Exception\HttpResponseException;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Response as IlluminateResponse;
use JWTFactory;
use App\Http\Controllers\Controller;
use App\DB\DeviceDB;

class DeviceController extends Controller {
	/**
	 * Create a new controller instance.
	 *
	 * @return void
	 */
	protected $app;
	
	/**
	 *
	 * @param \Laravel\Lumen\Application $app        	
	 */
	public function __construct(\Laravel\Lumen\Application $app) {
		$this->app = $app;
	}
	
	/**
	 * 查询设备信息
	 *
	 * @param Request $request        	
	 * @param unknown $device_no        	
	 * @return Ambigous <\Illuminate\Http\Response, \Laravel\Lumen\Http\ResponseFactory>
	 */
	public function query(Request $request, $device_no) {
		$device = DeviceDB::getDeviceInfo ( $request->user ()->uid, $device_no );
		$ua = $request->headers->get ( "User-Agent" );
		if (preg_match ( '/SIMCOM/i', $ua )) {
			$device->address = base64_encode ( iconv ( 'utf-8', 'gbk', $device->address ) );
			$device->company = base64_encode ( iconv ( 'utf-8', 'gbk', $device->company ) );
		}
		return responseData ( $device );
	}
	
	/**
	 * 查询设备信息列表
	 *
	 * @param Request $request        	
	 * @param unknown $uid        	
	 * @param unknown $page        	
	 * @param unknown $size        	
	 */
	public function queryList(Request $request, $uid) {
		$page = $request->has ( 'page' ) ? $request->input ( 'page' ) : 1;
		$size = $request->has ( 'size' ) ? $request->input ( 'size' ) : 5;
		$devices = DeviceDB::getDeviceList ( $uid, $page, $size );
		return responseListData ( $devices, DeviceDB::getDeviceListCount ( $uid ) );
	}
	
	/**
	 * 添加设备信息
	 *
	 * @param Request $request        	
	 */
	public function add(Request $request) {
		$jsondata = $request->getContent ();
		$data = json_decode ( $jsondata );
		
		DeviceDB::addDevice ( $data );
		return responseError ();
	}
	
	/**
	 * 删除设备信息
	 *
	 * @param Request $request        	
	 */
	public function delete(Request $request) {
		$jsondata = $request->getContent ();
		$data = json_decode ( $jsondata );
		
		DeviceDB::deleteDevice ( $data );
		return responseError ();
	}
	
	/**
	 * 更新设备信息
	 *
	 * @param Request $request        	
	 */
	public function update(Request $request) {
		$jsondata = $request->getContent ();
		$data = json_decode ( $jsondata );
		
		DeviceDB::updateDevice ( $data );
		return responseError ();
	}
}
